import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'

const baseURL = 'http://big-event-vue-api-t.itheima.net'
const instance = axios.create({
  baseURL,
  timeout: 10000
})
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    //携带token
    const useStore = useUserStore()
    if (useStore.token) {
      config.headers.Authorization = useStore.token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.data.code === 0) {
      return response
    }
    //处理业务失败
    ElMessage.error(response.data.message)
    return Promise.reject(response.data)
  },
  (err) => {
    //错误的特殊情况401 权限不足 token过期
    if (err.response?.status === 401) {
      router.push('/login')
    }

    //错误的默认情况
    ElMessage.error(err.data.message)
    return Promise.reject(err)
    //==============  错误处理  ====================
  }
)
export { baseURL }
export default instance
